//
//  SGWiFiViewController.m
//  SGWiFiUpload
//
//  Created by soulghost on 30/6/2016.
//  Copyright © 2016 soulghost. All rights reserved.
//

#import "SGWiFiViewController.h"
#import "SGWiFiView.h"
#import "HTTPServer.h"
#import "HYBIPHelper.h"
#import "SGWiFiUploadManager.h"
#import <YYKit/YYKit.h>
#import "AvKitController.h"
#import <SSZipArchive/SSZipArchive.h>
#import "VideoPlayerContainerView.h"

@interface SGWiFiViewController ()
@property (nonatomic, weak) SGWiFiView *wifiView;
@property(assign, nonatomic) BOOL isUpload;

@end

@implementation SGWiFiViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 开启返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Wi-Fi传书📖";
    self.view.backgroundColor = [UIColor whiteColor];
    // ☜ ☚⬅︎←👈🐯🐯
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"👈👈" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];
    
    UIButton *btnAction = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btnAction.frame = CGRectMake(0, 0, 44, 44);
    [btnAction addTarget:self action:@selector(askAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [btnAction setImage:[UIImage imageNamed:@"problem"] forState:(UIControlStateNormal)];
    [btnAction setTintColor:[UIColor blackColor]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btnAction];
    self.navigationItem.rightBarButtonItem.customView = btnAction;
    
    SGWiFiView *wifiView = [[SGWiFiView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:wifiView];
    self.wifiView = wifiView;
    wifiView.addressAction = ^(NSString *address) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"复制地址成功" message:nil preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确认" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string = address;
        }];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:nil];
        [alertVC addAction:cancle];
        [alertVC addAction:sure];
        [self presentViewController:alertVC animated:YES completion:nil];
    };
    
    UILabel *alertLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-44, self.view.bounds.size.width, 44)];
    [self.view addSubview:alertLabel];
    alertLabel.text = @"⚠️：传书过程中不要退出本页面！";
    alertLabel.textColor = [UIColor orangeColor];//[UIColor colorWithHexString:@"#EE5C42"];
    alertLabel.textAlignment = NSTextAlignmentCenter;
    alertLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:11];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    SGWiFiUploadManager *mgr = [SGWiFiUploadManager sharedManager];
    HTTPServer *server = mgr.httpServer;
    if (server.isRunning) {
        if ([HYBIPHelper deviceIPAdress] == nil) {
            [self.wifiView setAddress:@"Error, your Device is not connected to WiFi."];
            return;
        }
        NSString *ip_port = [NSString stringWithFormat:@"http://%@:%@",mgr.ip,@(mgr.port)];
        [self.wifiView setAddress:ip_port];
    } else {
        [self.wifiView setAddress:@"Error, Server Stopped"];
    }
}

- (void)dismiss {
    if (self.isUpload) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"请稍后..." message:@"正在上传文件" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
        [alertVC addAction:cancle];
        [self presentViewController:alertVC animated:YES completion:nil];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
        // [self dismissViewControllerAnimated:YES completion:nil];
        if (self.dismissBlock) { self.dismissBlock(); }
    }
}

- (void)startUpload:(NSString *)fileName {
    self.title = [NSString stringWithFormat:@"正在接收《%@》...",fileName];
    self.isUpload = YES;
    
    UIView *cusView = self.navigationItem.rightBarButtonItem.customView;
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
    [cusView addSubview:activityIndicator];
    activityIndicator.frame = cusView.bounds;
    activityIndicator.color = [UIColor redColor];
    activityIndicator.backgroundColor = [UIColor clearColor];
    activityIndicator.hidesWhenStopped = NO;
    [activityIndicator startAnimating];
}

- (void)stopUpload:(NSString *)fileName {
    self.title = [NSString stringWithFormat:@"《%@》接收完毕！",fileName];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.title = @"Wi-Fi传书📖";
        self.isUpload = NO;
        UIView *cusView = self.navigationItem.rightBarButtonItem.customView;
        for (UIView *subView in cusView.subviews) {
            if ([subView isKindOfClass:[UIActivityIndicatorView class]]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView *)subView;
                        [activityIndicator stopAnimating];
                        [subView removeFromSuperview];
                    });
                });
            }
        }
    });
}

- (void)askAction:(UIButton *)sender {
    AvKitController *videoVC = [AvKitController new];
    videoVC.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:videoVC animated:YES completion:nil];
    videoVC.urlVideo = @"http://www.restcy.com/source/guide_01.mp4";
}

@end

